// SimpleCountdown.ts
import { _decorator, Component, Label } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('DaoShuiPaiXu_Timer')
export class DaoShuiPaiXu_Timer extends Component {
      @property(Label)
      timeLabel: Label = null!;

      // @property
      totalTime: number = (60 * 3);

      @property
      autoStart: boolean = false;

      private currentTime: number = 0;
      private isRunning: boolean = false;
      private isPaused: boolean = false;

      onLoad() {
            this.currentTime = this.totalTime;
            this.updateDisplay();
      }

      start() {
            if (this.autoStart) {
                  this.startCountdown();
            }
      }

      update(dt: number) {
            if (!this.isRunning || this.isPaused) return;

            this.currentTime -= dt;

            if (this.currentTime <= 0) {
                  this.currentTime = 0;
                  this.isRunning = false;
                  this.onCountdownEnd();
            }

            this.updateDisplay();
      }

      startCountdown() {
            if (this.isRunning && !this.isPaused) return;

            if (this.isPaused) {
                  this.isPaused = false;
            } else {
                  this.isRunning = true;
            }
      }

      pauseCountdown() {
            if (!this.isRunning || this.isPaused) return;
            this.isPaused = true;
      }

      resumeCountdown() {
            if (!this.isRunning || !this.isPaused) return;
            this.isPaused = false;
      }

      resetCountdown() {
            this.isRunning = false;
            this.isPaused = false;
            this.currentTime = this.totalTime;
            this.updateDisplay();
      }

      setTime(seconds: number) {
            this.totalTime = seconds;
            this.currentTime = seconds;
            this.updateDisplay();
      }

      getRemainingTime(): number {
            return this.currentTime;
      }

      private updateDisplay() {
            if (!this.timeLabel) return;

            const minutes = Math.floor(this.currentTime / 60);
            const seconds = Math.floor(this.currentTime % 60);
            this.timeLabel.string = `${this.padZero(minutes)}:${this.padZero(seconds)}`;
      }

      private padZero(num: number): string {
            return num.toString().padStart(2, '0');
      }

      private onCountdownEnd() {
            console.log('倒计时结束------发送');
            // 这里可以添加倒计时结束的处理逻辑
            this.node.emit("countdown_end");
      }
}